import React, {useEffect, useState, useMemo} from 'react'

import {ProColumns} from '@ant-design/pro-components'

import {Button, Form, Space, message, Modal, Input, Popconfirm} from 'antd'
import AdvancedSearchFrom from '@/components/SearchForm/advancedSearchFrom'

import {getCodeList, remove, saveBitchCode, update} from '@/service/channel'

import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '300px'},
}

type DataSourceType = {
	id: React.Key
	title?: string
	labels?: {
		key: string
		label: string
	}[]
	state?: string
	// eslint-disable-next-line camelcase
	created_at?: string
	children?: DataSourceType[]
}

export default function edit({didtableId}: any) {
	const [formData, setFormData] = useState({})
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [tableList, setTableList] = useState<any[]>([])
	const [loading, setLoading] = useState(false)
	const [visible, setVisible] = useState(false)
	const [codeId, setCodeId] = useState('')
	const [type, setType] = useState('')
	const [cid, setCid] = useState('')
	const [form] = Form.useForm()
	const [currentPage, setCurrentPage] = useState({current: 1})

	const initialValues = useMemo(() => {
		setTimeout(() => {
			form.resetFields()
		}, 1)
		return {ditchCode: codeId}
	}, [codeId, visible])

	const getTabelValue = async (value: any, pagination?: any) => {
		setLoading(true)
		let values = value

		setFormData(values)
		const newPagination = pagination || {
			current: 1,
			size: params.size,
		}
		setParams(newPagination)
		values = {
			...values,
			...newPagination,
		}
		const res = await getCodeList(values)
		if (res?.data) {
			setTotal(res.data?.total || 0)
			if (res.data?.records) {
				setTableList(res.data?.records || [])
			}
		}
		setLoading(false)
	}
	useEffect(() => {
		getTabelValue({ditchId: didtableId})
	}, [didtableId])

	const onSave = async () => {
		try {
			const FormD = await form.validateFields()
			if (FormD.ditchCode) {
				const res = await saveBitchCode({
					ditchId: didtableId,
					ditchCode: FormD.ditchCode,
				})
				if (res.success) {
					getTabelValue(formData, params)
					setCodeId('')
					setCid('')
					setVisible(false)
					message.success(res.msg)
				} 
			} else {
				message.error('请输入code')
			}
		} catch (error) {
			// eslint-disable-next-line no-console
		}
	}

	const onEdit = async () => {
		try {
			const FormD = await form.validateFields()
			if (FormD.ditchCode) {
				const res = await update({
					id: cid,
					ditchId: didtableId,
					ditchCode: FormD.ditchCode,
				})
				if (res.success) {
					getTabelValue(formData, params)
					setCodeId('')
					setCid('')
					setVisible(false)
					message.success(res.msg)
				} 
			} else {
				message.error('请输入code')
			}
		} catch (error) {
			// eslint-disable-next-line no-console
		}
	}

	const columns: ProColumns<DataSourceType>[] = [
		{
			title: 'id',
			dataIndex: 'id',
			width: '30%',
		},
		{
			title: '渠道code码',
			dataIndex: 'ditchCode',
			width: '30%',
		},

		{
			title: '操作',
			valueType: 'option',
			width: '30%',
			render: (_: any, record: any) => (
				<Space size={12}>
					<Permissions permissionID="amc_merchantCenter_channel_codeedit">
						<Button
							type="link"
							onClick={() => {
								setCodeId(record.ditchCode)
								setCid(record.id)
								setType('edit')
								setVisible(true)
							}}>
							编辑
						</Button>
					</Permissions>

					<Popconfirm
						placement="topLeft"
						title="你确定要删除这条线索数据吗？"
						onConfirm={async () => {
							const res = await remove({ids: record.id})
							if (res.success) {
								getTabelValue(formData, params)
								message.success('删除成功')
							} 
						}}
						okText="确定"
						cancelText="取消">
						<Button type="link">删除</Button>
					</Popconfirm>
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '渠道code码',
					name: 'ditchCode',
					key: 'ditchCode',
					keys: 'id',
					title: 'name',
					placeholder: '请输入渠道code码',
				},
			],
		},
	]

	// 搜索
	const finish = (value: any) => {
		const info = {...value}
		getTabelValue(
			{...info, ditchId: didtableId},
			{
				current: 1,
				size: params.size,
			},
		)
		setCurrentPage({current: 1})
	}
	// 重置
	const reset = () => {
		getTabelValue(
			{ditchId: didtableId},
			{
				current: 1,
				size: params.size,
			},
		)
		setCurrentPage({current: 1})
	}

	return (
		<>
			<AdvancedSearchFrom
				formLayout={formItemLayout}
				onFinish={finish}
				onReset={reset}
				formItems={formItems}
				rows={3}
			/>
			<Space>
				<Permissions permissionID="amc_merchantCenter_channel_codeadd">
					<Button
						onClick={() => {
							setType('add')
							setVisible(true)
						}}>
						新增
					</Button>
				</Permissions>
			</Space>

			<CustomTable
				params={currentPage}
				columns={columns}
				total={total}
				pagination
				scroll={{x: 600}}
				callback={(pagination: any) => {
					getTabelValue(formData, pagination)
					setParams(pagination)
					const data = {
						current: pagination?.current,
					}
					setCurrentPage(data)
				}}
				loading={loading}
				dataSource={tableList}
			/>
			<Modal
				title="渠道code码"
				open={visible}
				onCancel={() => {
					setCodeId('')
					setCid('')
					setVisible(false)
				}}
				width={500}
				forceRender
				onOk={() => {
					if (type === 'add') {
						onSave()
					}
					if (type === 'edit') {
						onEdit()
					}
				}}>
				{visible ? (
					<Form
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						name="PersonalInformationFom"
						initialValues={initialValues}
						form={form}>
						<Form.Item label="code" name="ditchCode" required>
							<Input />
						</Form.Item>
					</Form>
				) : (
					<></>
				)}
			</Modal>
		</>
	)
}
